//! # 子协议层
//!
//! 子协议层(protocol)规定了子协议接口(Protocol)

use crate::consts::*;
use crate::id::Id;
use heapless::LinearMap;
use log::warn;
use spin::Lazy;
use spin::RwLock;

/// 协议池
static PROTOCOLS: Lazy<RwLock<LinearMap<u8, fn(remote: &Id, data: &[u8]), ProtocolLen>>> =
    Lazy::new(|| RwLock::new(LinearMap::new()));

/// 在协议池中注册一个协议
pub fn add_protocol(id: u8, when_recv: fn(remote: &Id, data: &[u8])) {
    if let Err(_) = PROTOCOLS.write().insert(id, when_recv) {
        panic!("too many protocol.");
    };
}
/// 分发数据到具体协议
pub fn distribute(id: u8, remote: &Id, data: &[u8]) {
    if let Some(when_recv) = PROTOCOLS.read().get(&id) {
        when_recv(remote, data);
    } else {
        warn!("unmp_protocol {} is not exist.", id);
    };
}
